<template>
  <div>
    <h1>WebSocket 广播消息示例</h1>
    <button @click="sendMessage">发送消息</button>
    <p v-if="receivedMessage">接收到的消息：{{ receivedMessage }}</p>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted } from 'vue';
import { ElNotification } from 'element-plus'

export default {
  setup() {
    const ws = ref(null);           // WebSocket 实例
    const receivedMessage = ref(''); // 存储接收到的消息

    // 初始化 WebSocket
    const initWebSocket = () => {
      ws.value = new WebSocket('ws://localhost:3300');

      ws.value.onopen = function () {
        // 客户端加入房间
        const joinMessage = JSON.stringify({ action: 'join', roomId: '6780c594fa1594a3ed30cc7' });
        ws.value.send(joinMessage);

        // 向房间发送消息
        // const sendMessage = JSON.stringify({ roomId: '6780c594fa1594a3ed30cc73', message: 'Hello, Room 1!' });
        // ws.value.send(sendMessage);
      };

      ws.value.onmessage = function (event) {
        const data = JSON.parse(event.data);
        console.log('Received message:', data.message);
      };


      ws.value.onclose = () => {
        console.log('WebSocket 连接已关闭');
      };

      ws.value.onerror = (error) => {
        console.error('WebSocket 错误:', error);
      };
    };

    // 发送消息到 WebSocket 服务器
    const sendMessage = () => {
      if (ws.value && ws.value.readyState === WebSocket.OPEN) {
        const message = JSON.stringify({
          roomId: '6780c594fa1594a3ed30cc73',
          message: 'Hello from Vue3!'
        })
        ws.value.send(message);
        console.log('已发送消息:', message);
      } else {
        console.error('WebSocket 未连接');
      }
    };

    // 初始化 WebSocket 连接
    onMounted(() => {
      initWebSocket();
    });

    // 组件卸载时关闭 WebSocket 连接
    onUnmounted(() => {
      if (ws.value) {
        ws.value.close();
      }
    });

    return {
      receivedMessage, // 显示接收到的消息
      sendMessage,     // 发送消息的方法
    };
  },
};
</script>

<style scoped>
/* 样式 */
</style>
